import java.util.Date;

public class MyFactory {
    public static void main(String[] args) {
        MyBuffer buffer=new MyBuffer();
        int producers=3;
        int consumers=5;
        for(int i=0;i<producers;i++){
            MyProducer producer=new MyProducer(buffer,"生产者"+i+"号");
            producer.start();
        }
        for(int i=0;i<consumers;i++){
            MyConsumer consumer=new MyConsumer(buffer,"消费者"+i+"号");
            consumer.start();
        }
    }
}
class SleepUtilities {
    public static void nap()
    {
        try {
            Thread.sleep((long)(Math.random()*1000));
        }catch (Exception e) {
            // TODO: handle exception
        }
    }
}
class MyProducer extends Thread implements Runnable{
    public MyBuffer buffer;
    String name;//生产者代号
    public MyProducer(MyBuffer myBuffer,String name){
        buffer=myBuffer;
        this.name=name;
    }
    @Override
    public void run(){
        Date message;
        while(true){
            message=new Date();
            SleepUtilities.nap();
            if(buffer.data<buffer.MAX){
                buffer.insert();
                System.out.println(name + "生产了一份产品----" + message);
                System.out.println("此时产品数量" + buffer.data);
            }
        }
    }
}
class MyConsumer extends Thread implements Runnable{
    public MyBuffer buffer;
    public String name;

    public MyConsumer(MyBuffer myBuffer,String name){
        this.buffer=myBuffer;
        this.name=name;
    }
    public void run(){
        Date message;
        while(true){
            SleepUtilities.nap();
            message=new Date();
            if(buffer.data>buffer.MIN){
                buffer.remove();
                System.out.println(name + "消费了一份产品----" + message);
                System.out.println("此时的产品数量"+buffer.data);
            }
        }
    }
}
class MyBuffer{
    final static int MAX=10;
    final static int MIN=0;
    int data=0;
    public MyBuffer(){
        data=0;
    }
    public void insert(){
        data++;
    }
    public void remove(){
        data--;
    }
}